﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts.Report;
using Kingdee.BOS.Core.Enums;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace PMAF.K3Cloud.SCM.Report.ServicePlugIn
{
    [Kingdee.BOS.Util.HotUpdate]
    [Description("销售出库按单综合统计表")]
    public class SaleGrossProfitReport : SysReportBaseService
    {
        public override void Initialize()
        {
            //初始化
            base.Initialize();
            //简单账表类型：普通、树形、分页
            ReportProperty.ReportType = ReportType.REPORTTYPE_NORMAL;
            //报表显示顺序字段
            //ReportProperty.IdentityFieldName = "FIDENTITYID";
            //是用插件创建临时表
            IsCreateTempTableByPlugin = true;
            //是否分组汇总
            ReportProperty.IsGroupSummary = true;
        }

        /// <summary>
        /// 报表头
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public override ReportTitles GetReportTitles(IRptParams filter)
        {
            base.GetReportTitles(filter);
            ReportTitles reportTitles = new ReportTitles();
            DynamicObject customFilter = filter.FilterParameter.CustomFilter;
            if (customFilter != null)
            {
                string aveProfitStart = customFilter["F_PMAF_AveProfitStart"].ToString();
                string aveProfitEnd = customFilter["F_PMAF_AveProfitEnd"].ToString();
                string aveProfit = string.Join("至", aveProfitStart, aveProfitEnd);
                string outStockStartDate = customFilter["F_PMAF_OutStockStartDate"].ToString();
                string outStockEndDate = customFilter["F_PMAF_OutStockEndDate"].ToString();
                string outStockDate = string.Join("至", outStockStartDate.Substring(0, 10), outStockEndDate.Substring(0, 10));
                string businessOrgNames = GetbusinessOrgNames(customFilter["F_PMAF_BusinessOrgs"].ToString());
                reportTitles.AddTitle("F_PMAF_BusinessOrgs", businessOrgNames);
                string saleMans = GetSaleMans((DynamicObjectCollection)customFilter["F_PMAF_SaleIds"]);
                string customerNames = GetSaleMans((DynamicObjectCollection)customFilter["F_PMAF_CustomerIds"]);
                string buyers = GetSaleMans((DynamicObjectCollection)customFilter["F_PMAF_PurchaseIds"]);
                reportTitles.AddTitle("F_PMAF_SaleMans", saleMans);
                reportTitles.AddTitle("F_PMAF_Customers", customerNames);
                reportTitles.AddTitle("F_PMAF_PurchaseIds", buyers);
                reportTitles.AddTitle("F_PMAF_AveProfit", aveProfit);
                reportTitles.AddTitle("F_PMAF_OutStockDate", outStockDate);
            }
            return reportTitles;
        }

        /// <summary>
        /// 设置报表列
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public override ReportHeader GetReportHeaders(IRptParams filter)
        {
            ReportHeader header = new ReportHeader();
            header.AddChild("FBILLNO", new LocaleValue("基础信息&出库单号", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FDATE", new LocaleValue("基础信息&出库日期", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FCUSTOMERNAME", new LocaleValue("基础信息&客户名称", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FSTOCKORGNAME", new LocaleValue("基础信息&组织", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FSALEMAN", new LocaleValue("基础信息&销售员", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("PURCHASENAME", new LocaleValue("基础信息&采购员", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FACTORYNAME", new LocaleValue("基础信息&油厂", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FCARRIERNAME", new LocaleValue("基础信息&运输公司", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("TRUCKNO", new LocaleValue("基础信息&车号", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FPRICEQTY", new LocaleValue("业务利润&销售数量", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("SALAVEPRICE", new LocaleValue("业务利润&销售单价（均）", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("REBATE", new LocaleValue("业务利润&工厂返点", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FALLAMOUNT", new LocaleValue("业务利润&销售金额", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("COSTAVEPRICE", new LocaleValue("业务利润&成本单价（均）", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("OUTSTOCKCOST", new LocaleValue("业务利润&销售成本", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("ACHIEVEMENTCOSTAMOUNT", new LocaleValue("业务利润&采购员毛利", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FCOMMISSION", new LocaleValue("业务利润&客户销售费用", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("TRANAMOUNT", new LocaleValue("业务利润&运费", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("DEDUCTION", new LocaleValue("业务利润&工厂扣款", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("PROFIT", new LocaleValue("业务利润&销售毛利", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("PURSALPROFIT", new LocaleValue("业务利润&购销总毛利", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("AVEPROFIT", new LocaleValue("业务利润&毛利（吨）", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("PROFITRATE", new LocaleValue("业务利润&毛利率", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FARBILLNO", new LocaleValue("应收超期及利息&应收单号", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FARDATE", new LocaleValue("应收超期及利息&应收日期", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FARENDDATE", new LocaleValue("应收超期及利息&应收到期日期", Context.UserLocale.LCID), SqlStorageType.Sqlvarchar);
            header.AddChild("FARAMOUNT", new LocaleValue("应收超期及利息&应收金额", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FRECEIVEAMOUNT", new LocaleValue("应收超期及利息&已结算金额", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("FNORECEIVEAMOUNT", new LocaleValue("应收超期及利息&未结算金额", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            header.AddChild("OVERDUEDATES", new LocaleValue("应收超期及利息&超期天数", Context.UserLocale.LCID), SqlStorageType.SqlInt);
            header.AddChild("INTERESTAMOUNT", new LocaleValue("应收超期及利息&应计利息", Context.UserLocale.LCID), SqlStorageType.SqlDecimal);
            return header;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="tableName"></param>
        public override void BuilderReportSqlAndTempTable(IRptParams filter, string tableName)
        {
            base.BuilderReportSqlAndTempTable(filter, tableName);
            DynamicObject customFilter = filter.FilterParameter.CustomFilter;
            string businessOrgIds = customFilter["F_PMAF_BusinessOrgs"].ToString();
            DynamicObjectCollection sales = (DynamicObjectCollection)customFilter["F_PMAF_SaleIds"];
            string salesStr = GetSales(sales);
            DynamicObjectCollection customers = (DynamicObjectCollection)customFilter["F_PMAF_CustomerIds"];
            string customersStr = GetCustomers(customers);
            decimal aveProfitStart = Convert.ToDecimal(customFilter["F_PMAF_AveProfitStart"]);
            decimal aveProfitEnd = Convert.ToDecimal(customFilter["F_PMAF_AveProfitEnd"]);
            string outStockStartDate = customFilter["F_PMAF_OutStockStartDate"].ToString();
            string outStockEndDate = customFilter["F_PMAF_OutStockEndDate"].ToString();
            DynamicObjectCollection buyers = (DynamicObjectCollection)customFilter["F_PMAF_PurchaseIds"];
            string buyersStr = GetBuyers(buyers);
            string sqlStr = string.Format(@"/*dialect*/
            SELECT
            t0.FBILLNO,
            t1.FARBILLNO,
            CONVERT(nvarchar(10),t0.FDATE,23) AS FDATE,
            t1.FARDATE,
            t1.FARENDDATE,
            t0.FCUSTOMERID,
            t3.FNAME AS FCUSTOMERNAME,
            t0.FSTOCKORGID,
            t4.FNAME AS FSTOCKORGNAME,
            t0.FSALEORGID,
            t0.FCARRIERID,
            t0.FSALESMANID,
            t8.FNAME AS FSALEMAN,
            t10.F_PMAF_EMPID AS PURCHASEID,
            t11.FNAME AS PURCHASENAME,
            t10.FACTORYNAME,
            t6.FNAME AS FCARRIERNAME,
            t0.FCARRIAGENO AS TRUCKNO,
            t1.FPRICEQTY,
            t1.FARAMOUNT+t1.FDISCOUNTAMOUNT AS FALLAMOUNT,
            t1.FCOSTAMTSUM,
            t1.PURORDERCOST,
            t1.OUTSTOCKCOST,
            t1.REBATE,
            t1.ACHIEVEMENTCOSTAMOUNT,
            t0.F_PMAF_SALECOMMISSION AS SALECOMMISSION,
            t0.F_PMAF_CUSTCOMMISSION AS FCOMMISSION,
            t0.F_PMAF_TRANAMOUNT AS TRANAMOUNT,
            t0.F_PMAF_DEDUCTION AS DEDUCTION,
            t1.FARAMOUNT,
            t1.FRECEIVEAMOUNT,
            t1.FARAMOUNT+t1.FDISCOUNTAMOUNT-t1.ACHIEVEMENTCOSTAMOUNT AS ACHIEVEMENTPROFIT,
            t1.OVERDUEDATES,
            t1.INTERESTAMOUNT,
            t1.FNORECEIVEAMOUNT,
            t0.F_PMAF_SALECOMMISSION,
            t0.F_PMAF_CUSTCOMMISSION,
            t0.F_PMAF_DEDUCTION,
            t0.F_PMAF_TRANAMOUNT,
            (t1.FARAMOUNT-t1.FARAMOUNT) AS PROFIT,
            (t1.FARAMOUNT-t1.FARAMOUNT)/t1.FARAMOUNT AS PROFITRATE
            INTO #TEMP1
            FROM T_SAL_OUTSTOCK t0
            LEFT JOIN(
            SELECT
            c1.FBILLNO AS FARBILLNO,
            c0.FSOURCEBILLNO,
            CONVERT(nvarchar(10),c1.FDATE,23) AS FARDATE,
            CONVERT(nvarchar(10),c1.FENDDATE,23) AS FARENDDATE,
            c1.FCUSTOMERID,
            c1.FSETTLEORGID,
            c1.FSALEORGID,
            sum(c0.FALLAMOUNT/c0.FPRICEQTY*c6.F_PMAF_SALEQTY) AS FARAMOUNT,
            sum(c6.F_PMAF_SALEQTY) AS FPRICEQTY,
            sum(c6.F_PMAF_SALEQTY*c5.FCOSTPRICE) AS FCOSTAMTSUM,
            sum(c6.F_PMAF_SALEQTY*c4.F_PMAF_PURPRICE) AS PURORDERCOST,
            sum(c6.F_PMAF_SALEQTY*c6.F_PMAF_DETAILPURCHASEPRICE) AS OUTSTOCKCOST,
            sum(c6.F_PMAF_SALEQTY*c4.F_PMAF_REBATE) AS REBATE,
            sum(c0.FDISCOUNTAMOUNT/c0.FPRICEQTY*c6.F_PMAF_SALEQTY) AS FDISCOUNTAMOUNT,
            sum(c0.FRECEIVEAMOUNT/c0.FPRICEQTY*c6.F_PMAF_SALEQTY) AS FRECEIVEAMOUNT,
            sum(c0.FNORECEIVEAMOUNT/c0.FPRICEQTY*c6.F_PMAF_SALEQTY) AS FNORECEIVEAMOUNT,
            c1.F_PMAF_OVERDUEDATES AS OVERDUEDATES,
            c1.F_PMAF_INTERESTAMOUNT AS INTERESTAMOUNT,
            sum(c6.F_PMAF_SALEQTY*c3.F_PMAF_ACHIEVEMENTPRICE) AS ACHIEVEMENTCOSTAMOUNT
            FROM T_AR_RECEIVABLEENTRY c0
            LEFT JOIN T_AR_RECEIVABLE c1 ON c1.FID=c0.FID
            LEFT JOIN T_SAL_OUTSTOCK c2 ON c0.FSOURCEBILLNO=c2.FBILLNO
            LEFT JOIN T_SAL_OUTSTOCKENTRY c3 ON c3.FID=c2.FID AND c3.FENTRYID=c0.FSRCROWID
            LEFT JOIN PMAF_t_PurchaseSn c4 ON c4.FID=c3.F_PMAF_PURCHASESN
            LEFT JOIN T_SAL_OUTSTOCKENTRY_F c5 ON c3.FID=c5.FID AND c5.FENTRYID=c3.FENTRYID
            LEFT JOIN PMAF_t_OUTSTOCKPURCHASESN c6 ON c6.FENTRYID=c3.FENTRYID
            WHERE c0.FSOURCETYPE='SAL_OUTSTOCK' AND c1.FDOCUMENTSTATUS='C'
            GROUP BY c1.FBILLNO,c0.FSOURCEBILLNO,c1.FDATE,c1.FENDDATE,c1.FCUSTOMERID,c1.FSETTLEORGID,c1.FSALEORGID,c1.F_PMAF_OVERDUEDATES,c1.F_PMAF_INTERESTAMOUNT
            ) t1 ON t1.FSOURCEBILLNO=t0.FBILLNO
            LEFT JOIN T_BD_CUSTOMER_L t3 ON t0.FCUSTOMERID=t3.FCUSTID
            LEFT JOIN T_ORG_ORGANIZATIONS_L t4 ON t4.FORGID=t0.FSTOCKORGID
            LEFT JOIN T_ORG_ORGANIZATIONS_L t5 ON t5.FORGID=t0.FSALEORGID
            LEFT JOIN T_BD_SUPPLIER_L t6 ON t6.FSUPPLIERID=t0.FCARRIERID
            LEFT JOIN T_SAL_OUTSTOCKFIN t7 ON t7.FID=t0.FID
            LEFT JOIN V_BD_SALESMAN_L t8 ON t8.fid=t0.FSALESMANID
            LEFT JOIN V_BD_SALESMAN t2 ON t2.fid=t0.FSALESMANID
            LEFT JOIN (
            SELECT
            c0.FID,
            sum(c1.F_PMAF_SALEQTY*c0.F_PMAF_ACHIEVEMENTPRICE) AS ACHIEVEMENTAMOUNT
            FROM T_SAL_OUTSTOCKENTRY c0
            LEFT JOIN PMAF_t_OUTSTOCKPURCHASESN c1 ON c1.FENTRYID=c0.FENTRYID
            GROUP BY c0.FID) t9 ON t9.FID=t0.FID
            LEFT JOIN
            (SELECT
            FBILLNO,
            F_PMAF_EMPID,
            FACTORYNAME
            FROM
            (SELECT
            FBILLNO,
            FREALQTY,
            F_PMAF_EMPID,
            FACTORYNAME,
            ROW_NUMBER() OVER (PARTITION BY FBILLNO ORDER BY FBILLNO ASC,FREALQTY DESC) AS RN
            FROM
            (SELECT
            t2.FBILLNO,
            SUM(t5.F_PMAF_SALEQTY) AS FREALQTY,
            t1.F_PMAF_EMPID,
            t4.FNAME AS FACTORYNAME
            FROM T_SAL_OUTSTOCKENTRY t0 
            LEFT JOIN PMAF_t_PurchaseSn t1 ON t1.FID=t0.F_PMAF_PURCHASESN
            LEFT JOIN T_SAL_OUTSTOCK t2 ON t2.FID=t0.FID
            LEFT JOIN T_BD_MATERIAL t3 ON t3.FMATERIALID=t0.FMATERIALID
            LEFT JOIN T_BD_MATERIALGROUP_L t4 ON t4.FID=t3.FMATERIALGROUP
            LEFT JOIN PMAF_t_OUTSTOCKPURCHASESN t5 ON t5.FENTRYID=t0.FENTRYID
            WHERE t2.FDOCUMENTSTATUS='C'
            AND t4.FLOCALEID=2052
            GROUP BY t2.FBILLNO,t1.F_PMAF_EMPID,t4.FNAME) t0) t1
            WHERE RN=1) t10 ON t10.FBILLNO=t0.FBILLNO
            LEFT JOIN V_BD_OPERATORSTAFF_L t11 ON t11.fid=t10.F_PMAF_EMPID
            WHERE t0.FDOCUMENTSTATUS='C'
            AND t3.FLOCALEID=2052
            AND t4.FLOCALEID=2052
            AND t5.FLOCALEID=2052
            AND t11.FLOCALEID=2052
            AND t7.FISGENFORIOS=0
            AND t0.FSTOCKORGID IN ({1})
            {2}{3}
            AND t0.FDATE>='{4}'
            AND t0.FDATE<='{5}';
            SELECT FBILLNO,CONVERT(date,FDATE) AS INTERESTDATE,
            CASE
                WHEN DATEDIFF(DAY,CONVERT(date,FDATE),CONVERT(date,GETDATE()))>0 THEN DATEDIFF(DAY,CONVERT(date,FDATE),CONVERT(date,GETDATE()))
                ELSE 0
            END AS OVERDUE
            INTO #TEMP2
            FROM T_AR_RECEIVABLE;
            UPDATE #TEMP1 SET #TEMP1.OVERDUEDATES=#TEMP2.OVERDUE FROM #TEMP1
            INNER JOIN #TEMP2 ON #TEMP1.FARBILLNO=#TEMP2.FBILLNO WHERE #TEMP1.FNORECEIVEAMOUNT<>0;
            UPDATE #TEMP1 SET INTERESTAMOUNT=FNORECEIVEAMOUNT*OVERDUEDATES*0.00011 WHERE INTERESTAMOUNT=0;
            UPDATE #TEMP1 SET PROFIT=FALLAMOUNT+REBATE-OUTSTOCKCOST-ACHIEVEMENTCOSTAMOUNT-F_PMAF_SALECOMMISSION-F_PMAF_CUSTCOMMISSION-F_PMAF_DEDUCTION-F_PMAF_TRANAMOUNT-INTERESTAMOUNT;
            UPDATE #TEMP1 SET PROFITRATE=PROFIT/FALLAMOUNT*100;
            SELECT
            ROW_NUMBER() OVER(ORDER BY FDATE,FBILLNO) AS FIDENTITYID,
            FBILLNO,
            FARBILLNO,
            FDATE,
            FARDATE,
            FARENDDATE,
            FCUSTOMERID,
            FCUSTOMERNAME,
            FSTOCKORGID,
            FSTOCKORGNAME,
            FSALEORGID,
            FCARRIERID,
            FSALESMANID,
            FSALEMAN,
            PURCHASEID,
            PURCHASENAME,
            FCARRIERNAME,
            TRUCKNO,
            FACTORYNAME,
            FPRICEQTY,
            ROUND(FALLAMOUNT, 2) AS FALLAMOUNT,
            ROUND(FALLAMOUNT/FPRICEQTY,2) AS SALAVEPRICE,
            ROUND(OUTSTOCKCOST, 2) AS OUTSTOCKCOST,
            ROUND(REBATE, 2) AS REBATE,
            ROUND(OUTSTOCKCOST/FPRICEQTY,2) AS COSTAVEPRICE,
            ROUND(FCOMMISSION, 2) AS FCOMMISSION,
            ROUND(SALECOMMISSION, 2) AS SALECOMMISSION,
            ROUND(TRANAMOUNT, 2) AS TRANAMOUNT,
            ROUND(DEDUCTION, 2) AS DEDUCTION,
            ROUND(PROFIT, 2) AS PROFIT,
            ROUND(PROFIT/FPRICEQTY, 2) AS AVEPROFIT,
            ROUND(PROFITRATE, 2) AS PROFITRATE,
            ROUND(ACHIEVEMENTCOSTAMOUNT, 2) AS ACHIEVEMENTCOSTAMOUNT,
            ROUND(PROFIT+ACHIEVEMENTCOSTAMOUNT, 2) AS PURSALPROFIT,
            OVERDUEDATES,
            ROUND(FARAMOUNT, 2) AS FARAMOUNT,
            ROUND(FRECEIVEAMOUNT, 2) AS FRECEIVEAMOUNT,
            ROUND(FNORECEIVEAMOUNT, 2) AS FNORECEIVEAMOUNT,
            ROUND(INTERESTAMOUNT, 2) AS INTERESTAMOUNT
            INTO {0}
            FROM #TEMP1
            WHERE PROFIT/FPRICEQTY>={6}
            AND PROFIT/FPRICEQTY<={7}{8};
            DROP TABLE #TEMP1;
            DROP TABLE #TEMP2;
            ", tableName, businessOrgIds, salesStr, customersStr, outStockStartDate, outStockEndDate, aveProfitStart, aveProfitEnd, buyersStr);
            DBUtils.ExecuteDynamicObject(Context, sqlStr);
        }

        /// <summary>
        /// 设置汇总列
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public override List<SummaryField> GetSummaryColumnInfo(IRptParams filter)
        {
            var result = base.GetSummaryColumnInfo(filter);
            result.Add(new SummaryField("FALLAMOUNT", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("OUTSTOCKCOST", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("REBATE", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FCOMMISSION", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("SALECOMMISSION", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("TRANAMOUNT", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("DEDUCTION", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("PROFIT", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("ACHIEVEMENTCOSTAMOUNT", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FARAMOUNT", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FRECEIVEAMOUNT", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FNORECEIVEAMOUNT", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("INTERESTAMOUNT", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FPRICEQTY", BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("PURSALPROFIT", BOSEnums.Enu_SummaryType.SUM));
            return result;
        }

        /// <summary>
        /// 客户过滤字符串 
        /// </summary>
        /// <param name="customers"></param>
        /// <returns></returns>
        private string GetCustomers(DynamicObjectCollection customers)
        {
            StringBuilder sb = new StringBuilder();
            if (customers.Count > 0)
            {
                sb.Append(" AND t0.FCUSTOMERID IN (");
                int i = 0;
                foreach (var item in customers)
                {
                    DynamicObject customer = (DynamicObject)item["F_PMAF_CustomerIds"];
                    sb.Append(customer["Id"]);
                    if (i < customers.Count - 1)
                    {
                        sb.Append(",");
                    }
                    i++;
                }
                sb.Append(")");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 销售员过滤字符串
        /// </summary>
        /// <param name="sales"></param>
        /// <returns></returns>
        private string GetSales(DynamicObjectCollection sales)
        {
            StringBuilder sb = new StringBuilder();
            if (sales.Count > 0)
            {
                sb.Append(" AND t2.FNUMBER IN (");
                int i = 0;
                foreach (var item in sales)
                {
                    DynamicObject sale = (DynamicObject)item["F_PMAF_SaleIds"];
                    sb.Append("'");
                    sb.Append(Convert.ToString(sale["NUMBER"]));
                    sb.Append("'");
                    if (i < sales.Count - 1)
                    {
                        sb.Append(",");
                    }
                    i++;
                }
                sb.Append(")");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 采购员过滤字符串
        /// </summary>
        /// <param name="buyers"></param>
        /// <returns></returns>
        private string GetBuyers(DynamicObjectCollection buyers)
        {
            StringBuilder sb = new StringBuilder();
            int i = 0;
            if (buyers.Count > 0)
            {
                sb.Append(" AND PURCHASENAME IN (");
                foreach(var item in buyers)
                {
                    DynamicObject buyer = (DynamicObject)item["F_PMAF_PurchaseIds"];
                    sb.Append("'").Append(buyer["Name"]).Append("'");
                    if(i < buyers.Count - 1)
                    {
                        sb.Append(',');
                    }
                    i++;
                }
                sb.Append(")");
            }
            return sb.ToString();
        }

        /// <summary>
        /// 取得业务组织名称
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string GetbusinessOrgNames(string str)
        {
            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(str))
            {
                string[] strArr = str.Split(',');
                int i = 0;
                foreach (string idStr in strArr)
                {
                    //设置组织过滤条件并查询组织
                    OQLFilter orgFilter = new OQLFilter
                    {
                        new OQLFilterHeadEntityItem() { FilterString = string.Format("FORGID = '{0}'", idStr) }
                    };
                    DynamicObject[] orgs = BusinessDataServiceHelper.Load(Context, "ORG_Organizations", null, orgFilter);
                    string orgName = orgs[0]["NAME"].ToString();
                    sb.Append(orgName);
                    if (i < strArr.Length - 1)
                    {
                        sb.Append("; ");
                    }
                    i++;
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 取得多选基础资料名称
        /// </summary>
        /// <param name="fields"></param>
        /// <returns></returns>
        private string GetSaleMans(DynamicObjectCollection baseDatas)
        {
            StringBuilder sb = new StringBuilder();
            if (baseDatas.Count > 0)
            {
                int i = 0;
                foreach (DynamicObject item in baseDatas)
                {
                    string dataEntityType = item.GetDataEntityType().ToString();
                    DynamicObject baseData = (DynamicObject)item[dataEntityType];
                    sb.Append(baseData["Name"]);
                    if (i < baseDatas.Count - 1)
                    {
                        sb.Append(";");
                    }
                    i++;
                }
            }
            return sb.ToString();
        }
    }
}
